const Router = require('koa-router')
const { TokenValdate } = require('../../validators/validator')
const { loginType } = require('../../lib/enum')
const { User } = require('../../models/user')
const { Success } = require('../../core/http-exception')
const { generateToken } = require('../../core/utils')
const { WXManager } = require('../../services/WX')
const router = new Router({
  prefix: '/v1/token',
})
//token
router.post('/', async (ctx, next) => {
  const x = await new TokenValdate().validate(ctx)
  let userInfo;
  if (x.get('body.type') === loginType.USER_PHONE) {
    userInfo = await phoneLogin(x.get('body.phone'), x.get('body.password'), x.get('body.type'))
  } else {
    userInfo = await WXManager.codeToToken(x.get('body.account'), x.get('body.encryptedData'), x.get('body.iv'))
  }

  // account:code

  ctx.body = {
    data: userInfo,
    code: 200
  }
})
async function phoneLogin(phone, pawss) {
  let user = await User.verifyPhonePass(phone, pawss)
  let token = generateToken(user.id, 2)
  console.log('user :>> ', user);
  return {
    token,
    ...user.dataValues
  }
}
module.exports = router
